package org.example.teaView;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

public class HandleAddTopic implements ActionListener {

    AddTopicView addTopicView;
    Socket socket=null;
    DataInputStream in=null;
    DataOutputStream out=null;
    Thread thread;
    public void setAddTopicView(AddTopicView addTopicView) {
        this.addTopicView = addTopicView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == addTopicView.add){
            String top =null;
            boolean isright = addTopicView.inputID.getText().length() == 0|| addTopicView.inputName.getText().length() == 0
                    || addTopicView.inputSelect_A.getText().length() == 0 || addTopicView.inputSelect_B.getText().length() == 0||
                    addTopicView.inputSelect_C.getText().length() == 0 || addTopicView.inputSelect_D.getText().length() == 0 ||
                    addTopicView.input_ans.getText().length() == 0;
            if (!isright){
                InetAddress address= null;
                socket=new Socket();
                thread=new Thread(addTopicView);
                try {
                    address = InetAddress.getByName("127.0.0.1");
                    InetSocketAddress socketAddress=new InetSocketAddress
                            (address,4331);
                    socket.connect(socketAddress);
                    in =new DataInputStream(socket.getInputStream());
                    out = new DataOutputStream(socket.getOutputStream());
                    thread.start();
                } catch (IOException ex) {
                    socket=new Socket();
                }
                top ="添加题目题目ID："+addTopicView.inputID.getText()+"题目内容："+addTopicView.inputName.getText()+
                        "选项A:"+addTopicView.inputSelect_A.getText()+"选项B:"+addTopicView.inputSelect_B.getText()+
                        "选项C:"+addTopicView.inputSelect_C.getText()+"选项D:"+addTopicView.inputSelect_D.getText()+
                        "答案:"+addTopicView.input_ans.getText();
                try {
                    out.writeUTF(top);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                addTopicView.hintMess.setText("添加成功！");
            }else {
                addTopicView.hintMess.setText("请完善题目相关信息");
            }

        } else if (e.getSource() == addTopicView.back) {
            addTopicView.setVisible(false);
            new Firstview();
        }

    }
}
